package com.opal.system.service.impl;

import com.opal.system.entity.table.OpalDept;
import com.opal.system.entity.table.OpalDeptExample;
import com.opal.system.entity.table.OrgDeptExtend;
import com.opal.system.mapper.mysql.OpalDeptMapper;
import com.opal.system.service.OpalDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class OpalDeptServiceImpl implements OpalDeptService {
    @Autowired
    private OpalDeptMapper opalDeptMapper;

    @Override
    public Object getAllOpalDept() {
        return  opalDeptMapper.selectByExample(new OpalDeptExample());
    }

    @Override
    public List<OpalDept> getOpalDept(String pkOrg) {
        OpalDeptExample opalDeptExample = new OpalDeptExample();
        opalDeptExample.createCriteria().andPkOrgEqualTo(pkOrg);
        return opalDeptMapper.selectByExample(opalDeptExample);
    }

    @Override
    public Object getDeptEasyUiTreeData(String pkOrg) {
        // 获取所有部门信息
        List<OpalDept> opalDept = this.getOpalDept(pkOrg);
        //转换给子类OrgDeptExtend
        List<OrgDeptExtend> orgDepts=new ArrayList<>();
        for(OpalDept o:opalDept){
            OrgDeptExtend e = new OrgDeptExtend();
            e.setPkDept(o.getPkDept());
            e.setPkFatherorg(o.getPkFatherorg());
            e.setName(o.getName());
            orgDepts.add(e);
        }
        // 存储map
        Map<String, OrgDeptExtend> mapOrgDept = new HashMap<String, OrgDeptExtend>();
        List<OrgDeptExtend> parent = new ArrayList<OrgDeptExtend>();
        for (OrgDeptExtend orgDept : orgDepts) {
            mapOrgDept.put(orgDept.getPkDept(), orgDept);
            if (orgDept.getPkFatherorg().equals("~")) {
                parent.add(orgDept);
            }
        }
        for (OrgDeptExtend orgDept : orgDepts) {
            // 从map中查找到父对象，把自己存进父对象的属性Children中
            OrgDeptExtend orgDeptParent = mapOrgDept.get(orgDept.getPkFatherorg());
            if (orgDeptParent != null) {
                orgDeptParent.setState("closed");
                orgDeptParent.getChildren().add(orgDept);
            }
        }
        return parent;
    }
}
